package vn.com.vega.chacha.v2;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import vn.com.vega.chacha.R;
import vn.com.vega.chacha.v2.receiver.NetworkStatusReceiver;
import vn.com.vega.music.clientserver.JsonSong;
import vn.com.vega.music.objects.Album;
import vn.com.vega.music.utils.AlbumUtil;
import vn.com.vega.music.utils.AlbumUtil.LikeAndUnLikeAlbumListener;
import vn.com.vega.music.utils.Util;
import vn.com.vega.music.view.adapter.AlbumdetailAdapter;
import vn.com.vega.music.view.adapter.MixAdapter;
import vn.com.vega.music.view.adapter.SongListAdapter;
import vn.com.vega.music.view.custom.BottomPlayerView;
import vn.com.vega.music.view.custom.BottomPlayerView.ShowHideBottomPlayerListener;
import vn.com.vega.music.view.custom.LoadingView;
import vn.com.vega.music.view.custom.LoadingView.RetryListener;
import vn.com.vega.music.view.custom.TopTaskbarView;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class AlbumDetail extends ActivityBase implements OnClickListener {
	public static final String ALBUM_KEY_NAME = "name of album";
	public static final String TAG_MENU_LIKE = "like this album";
	public static final String TAG_MENU_SHARE = "share this album";

	private ListView albumDetail;
	private MixAdapter adapter;
	private AlbumdetailAdapter albumdetailAdapter;
	private SongListAdapter songListAdapter;
	private View pinView;
	private TextView playAll;
	private TextView selectSongPlay;
	private LoadingView loadingData;
	private Album mAlbum;
	private LoadingListSongForAlbum loadingListSong;
	private TopTaskbarView mTopTaskbarView;
	private BottomPlayerView mBottomPlayerView;
	private View mViewReplacePlayer;
	private ISelectSongPlay selectSongPlayInterface;
	private Appinstant mApp;

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		mApp = (Appinstant) getApplication();
		setContentView(R.layout.album_detail);
		albumDetail = (ListView) findViewById(R.id.lv_album_detail);
		mTopTaskbarView = (TopTaskbarView) findViewById(R.id.topTaskbarView_album_detail);
		pinView = findViewById(R.id.pinview_album_detail);
		pinView.setVisibility(View.GONE);
		playAll = (TextView) findViewById(R.id.tv_play_all_song);
		selectSongPlay = (TextView) findViewById(R.id.tv_select_song_play);
		playAll.setOnClickListener(this);
		selectSongPlay.setOnClickListener(this);
		albumDetail = (ListView) findViewById(R.id.lv_album_detail);
		loadingData = (LoadingView) findViewById(R.id.loadingView_loading_album);
		loadingData.setRetryListener(retryListener);
		loadingData.setVisibility(View.GONE);

		String albumKeyname = getIntent().getStringExtra(ALBUM_KEY_NAME);
		if (!Util.checkStringIsemptyOrNull(albumKeyname)) {
			Appinstant app = (Appinstant) getApplication();
			mAlbum = (Album) app.tranportAlbum.get(albumKeyname);
		}
		if (mAlbum == null) {
			finish();
			return;
		}
		initTopTaskBar();
		mBottomPlayerView = (BottomPlayerView) findViewById(R.id.bottomPlayerView_album_detail);
		mViewReplacePlayer = findViewById(R.id.view_replace_bottom_player);
		mBottomPlayerView.setShowHideListener(showHideBottomPlayerListener);

		if (mAlbum.listSong == null || mAlbum.listSong.size() == 0) {
			loadListSong();
		} else {
			showAlbumDetail();
		}
	}

	private void initTopTaskBar() {
		mTopTaskbarView.showBackButton();
		mTopTaskbarView.showMainMenu(false);
		mTopTaskbarView.addExtractMenu(R.drawable.bt_menu_like_toptask_menu,
				likeClickListener, TAG_MENU_LIKE);
		mTopTaskbarView.addExtractMenu(R.drawable.bt_toptask_menu_share,
				shareClickListener, TAG_MENU_SHARE);
		if (mAlbum.isFavorite) {
			mTopTaskbarView.getExtractMenu(TAG_MENU_LIKE).setSelected(true);
		} else {
			mTopTaskbarView.getExtractMenu(TAG_MENU_LIKE).setSelected(false);
		}
	}

	LikeAndUnLikeAlbumListener likeAndUnLikeAlbumListener = new LikeAndUnLikeAlbumListener() {

		@Override
		public void unlikeSuccess(Album album) {
			// TODO Auto-generated method stub
			View menuLike = mTopTaskbarView.getExtractMenu(TAG_MENU_LIKE);
			menuLike.setSelected(false);
			showToast("Xóa album " + album.title
					+ " khỏi danh sách yêu thích thành công");
		}

		@Override
		public void unlikeFail(Album album, String errorMsg) {
			// TODO Auto-generated method stub
			View menuLike = mTopTaskbarView.getExtractMenu(TAG_MENU_LIKE);
			menuLike.setSelected(true);
			if (Util.checkStringIsemptyOrNull(errorMsg)) {
				showToast("Xóa album " + album.title
						+ " khỏi danh sách yêu thích thất bại");
			} else {
				showToast(errorMsg);
			}
		}

		@Override
		public void startDoUnlike(Album album) {
			// TODO Auto-generated method stub
			showToast("Đang thực hiện hủy yêu thích album " + album.title);
		}

		@Override
		public void startDoLike(Album album) {
			// TODO Auto-generated method stub
			showToast("Đang thêm album " + album.title
					+ " vào danh sách yêu thích");
		}

		@Override
		public void likeSuccess(Album album) {
			// TODO Auto-generated method stub
			View menuLike = mTopTaskbarView.getExtractMenu(TAG_MENU_LIKE);
			menuLike.setSelected(true);
			showToast("Thêm album " + album.title
					+ " vào danh sách yêu thích thành công");
		}

		@Override
		public void likeFail(Album album, String errorMsg) {
			// TODO Auto-generated method stub
			View menuLike = mTopTaskbarView.getExtractMenu(TAG_MENU_LIKE);
			menuLike.setSelected(false);
			if (Util.checkStringIsemptyOrNull(errorMsg)) {
				showToast("Thêm album " + album.title
						+ " vào danh sách yêu thích thất bại");
			} else {
				showToast(errorMsg);
			}
		}
	};

	View.OnClickListener likeClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			// TODO: check album is like or unlike before do anything
			if (mAlbum.isFavorite) {
				AlbumUtil.unLikeAlbum(AlbumDetail.this, mAlbum,
						likeAndUnLikeAlbumListener);
			} else {
				AlbumUtil.likeAlbum(AlbumDetail.this, mAlbum,
						likeAndUnLikeAlbumListener);
			}
		}
	};

	View.OnClickListener shareClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Util.share(mAlbum.shareMessage, AlbumDetail.this);
		}
	};

	ShowHideBottomPlayerListener showHideBottomPlayerListener = new ShowHideBottomPlayerListener() {

		@Override
		public void onShowBottomPlayer() {
			// TODO Auto-generated method stub
			mViewReplacePlayer.setVisibility(View.VISIBLE);
		}

		@Override
		public void onHideBottomPlayer() {
			// TODO Auto-generated method stub
			mViewReplacePlayer.setVisibility(View.GONE);
		}
	};

	OnScrollListener onScrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			if (firstVisibleItem >= AlbumdetailAdapter.HEADER_TYPE) {
				pinView.setVisibility(View.VISIBLE);
			} else {
				pinView.setVisibility(View.GONE);
			}
		}
	};

	RetryListener retryListener = new RetryListener() {

		@Override
		public void onRetry() {
			// TODO Auto-generated method stub
			loadListSong();
		}
	};

	private void showAlbumDetail() {
		albumdetailAdapter = new AlbumdetailAdapter(this, mAlbum);
		songListAdapter = new SongListAdapter(this, mAlbum.listSong, false,
				AlbumDetail.class.getName());
		List<BaseAdapter> listAdapter = new ArrayList<BaseAdapter>();
		listAdapter.add(albumdetailAdapter);
		listAdapter.add(songListAdapter);
		adapter = new MixAdapter(listAdapter);
		albumDetail.setAdapter(adapter);
		albumDetail.setOnScrollListener(onScrollListener);

		selectSongPlayInterface = new ISelectSongPlay() {

			@Override
			public void selectSongPlay() {
				// TODO Auto-generated method stub
				if (songListAdapter != null && songListAdapter.getCount() > 0) {
//					mApp.tranportString.put(SelecSongPlay.KEY_LIST_SONG_TITLE,
//							mAlbum.title);
					songListAdapter.selectSongPlay("ALbum: " + mAlbum.title);
				}
			}

			@Override
			public void playAllSong() {
				// TODO Auto-generated method stub
				if (songListAdapter != null && songListAdapter.getCount() > 0) {
					songListAdapter.playAllSong("Album: " + mAlbum.title);
				}
			}
		};
		albumdetailAdapter.setSelectSongPlayInterface(selectSongPlayInterface);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (loadingListSong != null) {
			loadingListSong.cancel(true);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		mBottomPlayerView.stopUpdate();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mBottomPlayerView.startUpdate();
	}

	private void loadListSong() {
		loadingData.startLoading();
		if (loadingListSong != null
				&& loadingListSong.getStatus() == Status.RUNNING) {
			return;
		}
		if (loadingListSong != null
				&& loadingListSong.getStatus() != Status.RUNNING) {
			loadingListSong.cancel(true);
		}
		loadingListSong = new LoadingListSongForAlbum(this);
		loadingListSong.execute();
	}

	static class LoadingListSongForAlbum extends AsyncTask<Void, Void, Void> {
		WeakReference<AlbumDetail> albumDetailRfc;
		private List<Object> listSong;

		public LoadingListSongForAlbum(AlbumDetail albumDetail) {
			albumDetailRfc = new WeakReference<AlbumDetail>(albumDetail);
		}

		private boolean checkAppIsLive() {
			AlbumDetail albumDetail = albumDetailRfc.get();
			if (albumDetail == null || albumDetail.isDestroy) {
				return false;
			}
			return true;
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			if (!checkAppIsLive()) {
				return null;
			}
			AlbumDetail albumDetail = albumDetailRfc.get();
			if (NetworkStatusReceiver.isConnected()) {
				JsonSong jos = JsonSong
						.loadSongListByAlbumId(albumDetail.mAlbum.id);

				if (jos.isSuccess()) {
					listSong = new ArrayList<Object>();
					listSong.addAll(jos.songs);
				} else {
					Log.e(AlbumDetail.class.getSimpleName(),
							jos.getErrorMessage());
					// message = jos.getErrorMessage();
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			if (isCancelled() || !checkAppIsLive()) {
				return;
			}
			final AlbumDetail albumDetail = albumDetailRfc.get();
			if (listSong == null) {
				albumDetail.loadingData.loadingFinish(false, null);
			} else if (listSong.size() == 0) {
				albumDetail.loadingData.loadingFinish(false,
						"Album không có bài hát nào!");
			} else {
				albumDetail.mAlbum.listSong = listSong;
				albumDetail.loadingData.loadingFinish(true, null);
				albumDetail.showAlbumDetail();
			}
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			if (!checkAppIsLive()) {
				return;
			}
			AlbumDetail albumDetail = albumDetailRfc.get();
			albumDetail.loadingData.startLoading();
		}
	}

	public interface ISelectSongPlay {
		public void playAllSong();

		public void selectSongPlay();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.tv_play_all_song:
			if (selectSongPlayInterface != null) {
				selectSongPlayInterface.playAllSong();
			}
			break;
		case R.id.tv_select_song_play:
			if (selectSongPlayInterface != null) {
				selectSongPlayInterface.selectSongPlay();
			}

		default:
			break;
		}
	}

}
